package com.example.rabbitmq_producer.msg.service.impl;

import com.example.rabbitmq_common.config.RabbitMQConfigConstants;
import com.example.rabbitmq_common.config.RabbitMQConfigConstants;
import com.example.rabbitmq_common.vo.UserVo;
import com.example.rabbitmq_producer.msg.service.RabbitMQService;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName RabbitMQServiceImpl
 * @Description TODO
 * @Author gql
 * @Date 2023/3/10 17:48
 **/
@Slf4j
@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * @param msg
     * @return
     */
    @Override
    public String sendMsg(String msg) {

        try {
            String msgId = UUID.randomUUID().toString().replace("-","");
            String sendTime = sdf.format(new Date());
            Map<String,Object> map = new HashMap<>();
            map.put("msgId",msgId);
            map.put("sendTime",sendTime);
            map.put("msg",msg);
            rabbitTemplate.convertAndSend(RabbitMQConfigConstants.DIRECT_EXCHANGE,RabbitMQConfigConstants.DIRECT_ROUTING,map);
            return "ok";
        } catch (Exception e) {
            log.error(e.getMessage(),e);
           return "error";
        }
    }

    @Override
    public String sendBody(UserVo vo) {
        rabbitTemplate.convertAndSend(RabbitMQConfigConstants.DIRECT_EXCHANGE,RabbitMQConfigConstants.DIRECT_ROUTING,vo);
        return vo.toString();
    }
}
